// pages/index/index.js
const api = require('../../utils/api.js');
const util = require('../../utils/util.js');
const { regionSelector } = require('../../utils/region.js');
const app = getApp();

Page({
  // 页面数据
  data: {
    // 当前选中的Tab
    selectedTab: 'verified',
    
    // 推荐用户列表 + 3D样式
    recommendationList: [],
    swiperCurrent: 0,
    recommendStyles: [],
    // 3D 环形推荐（Carousel）
    ringItems: [],
    radius: 520,       // rpx
    baseAngle: 0,      // 当前环的旋转基角
    currentIndex: 0,   // 中央索引
    stepAngle: 40,     // 每张之间角度（会在 initRing 中按 n 自动设置）
    transitionMs: 280, // 过渡时间
    _touchStartX: 0,
    _lastAngle: 0,
    _animating: false,

    // three.js 相关
    threeEnabled: false,
    _three: null,         // THREE namespace
    _renderer: null,
    _scene: null,
    _camera: null,
    _ringGroup: null,
    _texLoader: null,
    _dragState: { x0: 0, baseAngle: 0, t0: 0, moved: false },
    
    // 用户列表
    userList: [],
    
    // 分页信息
    pageNum: 1,
    pageSize: 10,
    hasMore: true,
    loading: false,
    
    // 筛选相关
    showFilterModal: false,
    filterData: {
      gender: '',
      ageRange: {
        minAge: 18,
        maxAge: 60
      },
      heightRange: {
        minHeight: 150,
        maxHeight: 200
      },
      weightRange: {
        minWeight: 80,
        maxWeight: 200
      },
      maritalStatus: '',
      educationRange: {
        minEducation: '',
        maxEducation: ''
      },
      incomeRange: {
        minIncome: 0,
        maxIncome: 100
      },
      occupation: '',
      hometownPreference: [],
      currentResidencePreference: [],
      parentsHasPension: false
    },
    
    // 筛选选项
    genderOptions: ['男', '女'],
    educationOptions: [],
    hometownOptions: [],
    residenceOptions: [],
    educationIndex: 0, // legacy, kept for compatibility
    // Picker indices/options
    genderIndex: 0,
    maritalStatusOptions: [],
    maritalStatusIndex: 0,
    occupationOptions: [],
    
    // 省市区三级联动数据
    provinceOptions: [],
    // 籍贯相关
    hometownCityOptions: [],
    hometownDistrictOptions: [],
    hometownProvinceIndex: 0,
    hometownCityIndex: 0,
    hometownDistrictIndex: 0,
    hometownSelectedText: '',
    // 现居地相关
    residenceCityOptions: [],
    residenceDistrictOptions: [],
    residenceProvinceIndex: 0,
    residenceCityIndex: 0,
    residenceDistrictIndex: 0,
    residenceSelectedText: '',
    
    // 常见地址快速选择
    commonHometownAddresses: [],
    commonResidenceAddresses: [],
    occupationIndex: 0,
    ageOptions: [],
    ageMinIndex: 0,
    ageMaxIndex: 0,
    eduMinIndex: 0,
    eduMaxIndex: 0,
    heightOptions: [],
    heightMinIndex: 0,
    heightMaxIndex: 0,
    incomeOptions: [],
    incomeMinIndex: 0,
    incomeMaxIndex: 0,
    // 可拖拽搜索图标坐标（默认右下角）
    searchIconX: 600,
    searchIconY: 900,
    // 可搜索职业选择
    showOccupationModal: false,
    occupationSearchQuery: '',
    filteredOccupationOptions: [],
    
    // 今日送花状态
    todayFlowerSent: {},
    
    // 网络状态
    networkError: false,
    showNetworkStatus: false,
    networkStatusText: ''
  },

  // ================= CSS 3D 环（回退方案） =================
  // 初始化环（根据推荐数量设置步进角，并重算样式）
  initRing() {
    const n = (this.data.recommendationList || []).length;
    if (!n) {
      this.setData({ ringItems: [] });
      return;
    }
    const step = 360 / n;
    this.setData({ stepAngle: step, baseAngle: 0 }, () => {
      this.computeRingStyles(0);
    });
  },

  // 按当前 baseAngle 计算每个卡片的角度、缩放、透明与层级
  computeRingStyles(baseAngle = 0) {
    const { recommendationList, stepAngle, currentIndex } = this.data;
    const n = recommendationList.length;
    if (!n) {
      this.setData({ ringItems: [] });
      return;
    }
    const items = recommendationList.map((user, i) => {
      let deltaIndex = i - currentIndex;
      if (deltaIndex > n / 2) deltaIndex -= n;
      if (deltaIndex < -n / 2) deltaIndex += n;
      const angle = deltaIndex * stepAngle + baseAngle;
      const dist = Math.abs(deltaIndex);
      const scale = Math.max(0.78, 1 - 0.12 * dist);
      const opacity = Math.max(0.5, 1 - 0.20 * dist);
      const zIndex = 100 - dist;
      return { ...user, angle, scale, opacity, zIndex };
    });
    this.setData({ ringItems: items, baseAngle });
  },

  // 触摸开始（CSS 环）
  onRingTouchStart(e) {
    if (!e || !e.changedTouches || !e.changedTouches[0]) return;
    this.data._touchStartX = e.changedTouches[0].pageX;
    this.data._lastAngle = this.data.baseAngle || 0;
  },
  // 触摸移动（CSS 环）
  onRingTouchMove(e) {
    if (!e || !e.changedTouches || !e.changedTouches[0]) return;
    const moveX = e.changedTouches[0].pageX;
    const dx = moveX - this.data._touchStartX;
    const pxToDeg = 0.25; // 灵敏度：像素到角度
    const newAngle = (this.data._lastAngle || 0) + dx * pxToDeg;
    this.computeRingStyles(newAngle);
  },
  // 触摸结束（CSS 环）
  onRingTouchEnd() {
    this.snapToNearest();
  },

  // 吸附到最近卡片（CSS 环）
  snapToNearest() {
    const { baseAngle, stepAngle, currentIndex, recommendationList } = this.data;
    const n = (recommendationList || []).length;
    if (!n) return;
    const delta = -baseAngle / stepAngle;
    let nearest = Math.round(currentIndex + delta);
    while (nearest < 0) nearest += n;
    nearest = nearest % n;
    this.rotateToIndex(nearest, false);
  },

  // 旋转到指定索引（CSS 环）
  rotateToIndex(targetIndex, withBounce = false) {
    const { currentIndex, stepAngle, baseAngle, recommendationList } = this.data;
    const n = (recommendationList || []).length;
    if (!n || this.data._animating) return;
    let deltaIndex = targetIndex - currentIndex;
    if (deltaIndex > n / 2) deltaIndex -= n;
    if (deltaIndex < -n / 2) deltaIndex += n;
    const deltaAngle = -deltaIndex * stepAngle;
    const newAngle = baseAngle + deltaAngle;
    this.data._animating = true;
    this.setData({ transitionMs: 280 }, () => {
      this.computeRingStyles(newAngle);
      setTimeout(() => {
        this.setData({ currentIndex: targetIndex, baseAngle: 0 }, () => {
          this.computeRingStyles(0);
          // 取消反弹动画：直接结束
          this.data._animating = false;
        });
      }, this.data.transitionMs);
    });
  },

  // 点击卡片（CSS 环）
  onRingCardTap(e) {
    const tappedIndex = e.currentTarget && e.currentTarget.dataset
      ? e.currentTarget.dataset.index
      : undefined;
    if (typeof tappedIndex !== 'number') return;
    // 取消反弹：第二个参数 false
    this.rotateToIndex(tappedIndex, false);
  },

  onLoad(options) {
    console.log('首页加载');
    this.initData();
    this.checkNetworkAndLoadData();
    // 还原拖拽位置或按设备尺寸给默认值
    const saved = wx.getStorageSync('searchIconPos');
    if (saved && typeof saved.x === 'number' && typeof saved.y === 'number') {
      this.setData({ searchIconX: saved.x, searchIconY: saved.y });
    } else {
      const sys = wx.getSystemInfoSync();
      const x = Math.max(0, sys.windowWidth - 72);
      const y = Math.max(0, sys.windowHeight - 160);
      this.setData({ searchIconX: x, searchIconY: y });
    }
  },

  // 检查网络连接并加载数据
  async checkNetworkAndLoadData() {
    try {
      // 进行网络诊断
      const diagnosis = await api.diagnoseNetwork();
      console.log('网络诊断结果:', diagnosis);
      
      if (diagnosis.issues.length > 0) {
        console.warn('检测到网络问题:', diagnosis.issues);
        
        // 显示网络状态提示
        this.setData({
          showNetworkStatus: true,
          networkStatusText: diagnosis.issues.join(' | '),
          networkError: true
        });
        
        // 延迟3秒后自动隐藏提示
        setTimeout(() => {
          this.setData({ showNetworkStatus: false });
        }, 3000);
        return;
      }
      
      // 网络正常，尝试加载真实数据
      console.log('网络连接正常，加载真实数据');
      this.loadRecommendations();
      this.loadUserList();
      
    } catch (error) {
      console.error('网络检查失败:', error);
      wx.showModal({
        title: '网络连接问题',
        content: '无法连接到网络，将使用离线模式',
        showCancel: false,
        success: () => {
          // 网络问题，无法加载数据
          console.log('网络连接失败，无法加载数据');
        }
      });
    }
  },


  onShow() {
    console.log('[onShow] Page is being shown. Triggering resize logic.');
    // 检查登录状态和送花状态
    this.checkFlowerStatus();
    
    // 确保在页面显示时调整画布大小
    if (this.data.threeEnabled) {
      console.log('[onShow] Three.js is enabled, scheduling resize...');
      // 使用setTimeout确保DOM已准备好
      setTimeout(() => {
        console.log('[onShow] Calling resizeThreeCanvas...');
        this.resizeThreeCanvas();
      }, 100);
    }
    
    // 放大镜默认展示在页面右侧中间（每次进入页面都重置）
    try {
      const sys = wx.getSystemInfoSync();
      // 初始放置在中间的左侧
      const offsetX = 24; // 距左侧偏移
      const offsetY = 60; // 垂直半高估算
      const x = Math.max(0, offsetX);
      const y = Math.max(0, Math.floor(sys.windowHeight / 2) - offsetY);
      this.setData({ searchIconX: x, searchIconY: y });
    } catch (e) {}

    // 解决从其他页面返回后 three.js 画布尺寸变化导致的卡片变形/变大
    // 使用 nextTick + 双次延迟，确保布局稳定后再同步尺寸（针对 iOS）
    wx.nextTick(() => {
      this.resizeThreeCanvas();
      setTimeout(() => this.resizeThreeCanvas(), 140);
    });
  },

  onPullDownRefresh() {
    console.log('下拉刷新');
    this.refreshData();
  },

  onReachBottom() {
    console.log('上拉加载更多');
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreData();
    }
  },

  // 初始化数据
  initData() {
    const constants = app.globalData.constants;
    
    // 初始化省市区数据
    const provinceOptions = regionSelector.getProvinces();
    const hometownCityOptions = regionSelector.getCitiesByProvince(provinceOptions[0]);
    const hometownDistrictOptions = regionSelector.getDistrictsByCity(provinceOptions[0], hometownCityOptions[0]);
    const residenceCityOptions = regionSelector.getCitiesByProvince(provinceOptions[0]);
    const residenceDistrictOptions = regionSelector.getDistrictsByCity(provinceOptions[0], residenceCityOptions[0]);
    
    // 初始化常见地址
    const commonHometownAddresses = regionSelector.getCommonAddresses('hometown');
    const commonResidenceAddresses = regionSelector.getCommonAddresses('residence');
    
    this.setData({
      educationOptions: constants.educations,
      hometownOptions: constants.hometowns,
      residenceOptions: constants.residences,
      selectedTab: app.globalData.appState.selectedTab || 'verified',
      maritalStatusOptions: constants.maritalStatus,
      occupationOptions: constants.occupations,
      
      // 省市区数据
      provinceOptions: provinceOptions,
      hometownCityOptions: hometownCityOptions,
      hometownDistrictOptions: hometownDistrictOptions,
      residenceCityOptions: residenceCityOptions,
      residenceDistrictOptions: residenceDistrictOptions,
      
      // 常见地址
      commonHometownAddresses: commonHometownAddresses,
      commonResidenceAddresses: commonResidenceAddresses,
    });

    // 初始化年龄选项 18-60
    const ages = [];
    for (let a = 18; a <= 60; a++) ages.push(a);
    this.setData({
      ageOptions: ages,
      ageMinIndex: 0,
      ageMaxIndex: ages.length - 1,
    });

    // 初始化身高选项 150-200
    const heights = [];
    for (let h = 150; h <= 200; h++) heights.push(h);
    this.setData({
      heightOptions: heights,
      heightMinIndex: 0,
      heightMaxIndex: heights.length - 1,
    });

    // 初始化收入选项 0-100 (步进5)
    const incomes = [];
    for (let i = 0; i <= 100; i += 5) incomes.push(i);
    this.setData({
      incomeOptions: incomes,
      incomeMinIndex: 0,
      incomeMaxIndex: incomes.length - 1,
    });
  },

  // 检查送花状态
  checkFlowerStatus() {
    // 从API检查今日送花状态
    const todayFlowerKey = `todayFlower_${util.formatDate(new Date())}`;
    const todayFlowerSent = wx.getStorageSync(todayFlowerKey) || {};
    this.setData({ todayFlowerSent });
    
    // 更新用户列表中的送花状态
    this.updateFlowerStatus();
  },

  // 更新送花状态
  updateFlowerStatus() {
    const { userList, todayFlowerSent } = this.data;
    const updatedList = userList.map(user => ({
      ...user,
      todayFlowerSent: todayFlowerSent[user.userNum] || false
    }));
    this.setData({ userList: updatedList });
  },

  // Tab切换
  onTabChange(e) {
    const tab = e.currentTarget.dataset.tab;
    if (tab !== this.data.selectedTab) {
      this.setData({ 
        selectedTab: tab,
        pageNum: 1,
        userList: [],
        hasMore: true
      });
      app.globalData.appState.selectedTab = tab;
      if (tab === 'verified') {
        if (this.data.recommendationList.length === 0) {
          this.loadRecommendations();
        } else {
          // 回到 verified，确保环形样式正确
          this.initRing();
          // three 渲染时同步调整尺寸并重建
          wx.nextTick(() => {
            this.resizeThreeCanvas();
            setTimeout(() => this.resizeThreeCanvas(), 140);
          });
          if (this.data.threeEnabled && this.data._three && this.data._ringGroup && this.data._texLoader) {
            this.buildThreeRing(this.data._three, this.data._ringGroup, this.data._texLoader);
          }
        }
      }
      this.loadUserList();
    }
  },

  // 加载推荐用户（调用后端推荐接口）
  async loadRecommendations() {
    if (this.data.selectedTab !== 'verified') return; // 待验证用户不展示推荐
    try {
      wx.showLoading({ title: '加载推荐...' });
      const res = await api.getRecommendUserprofile();
      
      const processRecommendations = (recommendations) => {
        const list = recommendations.map(item => ({
          ...item,
          avatar: item.avatar || util.getDefaultAvatar(item.gender)
        }));
        
        this.setData({ recommendationList: list }, () => {
          // 尝试初始化three.js
          this.tryInitThree();
          
          // 确保CSS回退始终可用
          this.initRing();
          
          // 如果three.js初始化成功，则构建3D环
          if (this.data.threeEnabled && this.data._three && this.data._ringGroup && this.data._texLoader) {
            try {
              this.buildThreeRing(this.data._three, this.data._ringGroup, this.data._texLoader);
            } catch (e) {
              console.error('构建3D环失败，回退到CSS', e);
              this.setData({ threeEnabled: false });
            }
          }
        });
      };
      
      if (res && res.code === 0 && res.data && Array.isArray(res.data.recommendList)) {
        processRecommendations(res.data.recommendList);
      } else {
        // 推荐数据为空
        processRecommendations([]);
      }
    } catch (error) {
      console.error('加载推荐用户失败:', error);
      wx.showToast({ title: '加载推荐失败', icon: 'error' });
      this.setData({ recommendationList: [] });
    } finally {
      wx.hideLoading();
    }
  },

  // 尝试初始化three.js
  tryInitThree: function() {
    if (this.data.threeEnabled) return;
    
    try {
      const THREE = require('threejs-miniprogram');
      console.log('three.js module loaded successfully');
      this.initThree(THREE);
    } catch (e) {
      console.warn('threejs-miniprogram 未就绪，使用 CSS 回退', e);
      this.setData({ threeEnabled: false }, () => {
        // 确保CSS回退被正确初始化
        if (this.data.recommendationList && this.data.recommendationList.length > 0) {
          this.initRing();
        }
      });
    }
  },

  // 初始化three.js
  initThree: function(THREE) {
    console.log('Initializing three.js renderer...');

    const query = wx.createSelectorQuery();
    query.select('#webgl').node().exec(res => {
      if (!res || !res[0] || !res[0].node) {
        console.warn('未获取到 canvas 节点');
        return;
      }
      const canvas = res[0].node;
      const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true });
      const sys = wx.getSystemInfoSync();
      const dpr = sys.pixelRatio || 1;
      const logicalW = res[0].width || 300;
      const logicalH = res[0].height || 300;
      // 同步 backing store 与 DPR，renderer 保持 1，避免 iOS 返回后拉伸
      canvas.width = Math.max(1, Math.floor(logicalW * dpr));
      canvas.height = Math.max(1, Math.floor(logicalH * dpr));
      // 使用设备 DPR 提升清晰度，同时我们已同步 backing store，避免拉伸
      renderer.setPixelRatio(dpr);
      renderer.setSize(logicalW, logicalH, false);

      const scene = new THREE.Scene();
      const camera = new THREE.PerspectiveCamera(45, logicalW / logicalH, 0.1, 1000);
      camera.position.set(0, 0, 28);

      const ambient = new THREE.AmbientLight(0xffffff, 0.9);
      scene.add(ambient);
      const dir = new THREE.DirectionalLight(0xffffff, 0.6);
      dir.position.set(5, 10, 7);
      scene.add(dir);

      const ringGroup = new THREE.Group();
      scene.add(ringGroup);

      const texLoader = new THREE.TextureLoader();
      this.buildThreeRing(THREE, ringGroup, texLoader);

      const loop = () => {
        renderer.render(scene, camera);
        canvas.requestAnimationFrame(loop);
      };
      canvas.requestAnimationFrame(loop);

      this.setData({ threeEnabled: true });
      this.data._three = THREE;
      this.data._renderer = renderer;
      this.data._scene = scene;
      this.data._camera = camera;
      this.data._ringGroup = ringGroup;
      this.data._texLoader = texLoader;
    });
  },

  buildThreeRing(THREE, ringGroup, texLoader) {
    while (ringGroup.children.length) ringGroup.remove(ringGroup.children[0]);
    const list = this.data.recommendationList || [];
    if (!list.length) return;
    const n = list.length;
    const radius = 16;
    const cardW = 8, cardH = 4.8;
    const tasks = [];
    for (let i = 0; i < n; i++) {
      const user = list[i];
      tasks.push(this._createCardTexture(THREE, user));
    }
    Promise.all(tasks).then(textures => {
      for (let i = 0; i < n; i++) {
        const angle = (i / n) * Math.PI * 2;
        const x = Math.cos(angle) * radius;
        const z = Math.sin(angle) * radius;
        const geom = new THREE.PlaneGeometry(cardW, cardH);
        const map = textures[i];
        const mat = map
          ? new THREE.MeshBasicMaterial({ map, transparent: true })
          : new THREE.MeshBasicMaterial({ color: 0xdddddd });
        const mesh = new THREE.Mesh(geom, mat);
        mesh.position.set(x, 0, z);
        mesh.lookAt(0, 0, 0);
        mesh.rotation.y += Math.PI;
        mesh.userData = { index: i };
        ringGroup.add(mesh);
      }
    }).catch(() => {
      // 失败兜底：使用纯色方块，避免空白
      for (let i = 0; i < n; i++) {
        const angle = (i / n) * Math.PI * 2;
        const x = Math.cos(angle) * radius;
        const z = Math.sin(angle) * radius;
        const geom = new THREE.PlaneGeometry(cardW, cardH);
        const mat = new THREE.MeshBasicMaterial({ color: 0xdddddd });
        const mesh = new THREE.Mesh(geom, mat);
        mesh.position.set(x, 0, z);
        mesh.lookAt(0, 0, 0);
        mesh.rotation.y += Math.PI;
        mesh.userData = { index: i };
        ringGroup.add(mesh);
      }
    });
  },

  // 生成“头像+姓名+年龄”的合成纹理
  _createCardTexture(THREE, user) {
    return new Promise((resolve) => {
      try {
        const off = wx.createOffscreenCanvas({ type: '2d', width: 512, height: 320 });
        const ctx = off.getContext('2d');
        // 背景
        ctx.fillStyle = 'rgba(255,255,255,1)';
        this._roundRect(ctx, 0, 0, 512, 320, 24);
        ctx.fill();

        // 左侧头像圆框
        const avatarSize = 220; // px
        const avatarX = 40;
        const avatarY = 50;
        const avatarCX = avatarX + avatarSize / 2;
        const avatarCY = avatarY + avatarSize / 2;
        ctx.save();
        ctx.beginPath();
        ctx.arc(avatarCX, avatarCY, avatarSize / 2, 0, Math.PI * 2);
        ctx.closePath();
        ctx.clip();

        const img = off.createImage();
        const avatarUrl = user.avatar || util.getDefaultAvatar(user.gender);
        img.onload = () => {
          try {
            ctx.drawImage(img, avatarX, avatarY, avatarSize, avatarSize);
          } catch (e) {}
          ctx.restore();
          // 文本信息
          ctx.fillStyle = '#111';
          ctx.font = 'bold 44px -apple-system,Helvetica,Arial';
          ctx.textBaseline = 'top';
          const name = user.name || '匿名';
          const age = (user.age || '') + '岁';
          ctx.fillText(name, 300, 80);
          ctx.fillStyle = '#555';
          ctx.font = 'normal 36px -apple-system,Helvetica,Arial';
          ctx.fillText(age, 300, 150);

          // 构建纹理
          const tex = new THREE.CanvasTexture(off);
          tex.minFilter = THREE.LinearFilter;
          resolve(tex);
        };
        img.onerror = () => {
          // 图像加载失败也返回纯文本卡片
          ctx.restore();
          ctx.fillStyle = '#111';
          ctx.font = 'bold 44px -apple-system,Helvetica,Arial';
          const name = user.name || '匿名';
          const age = (user.age || '') + '岁';
          ctx.fillText(name, 300, 80);
          ctx.fillStyle = '#555';
          ctx.font = 'normal 36px -apple-system,Helvetica,Arial';
          ctx.fillText(age, 300, 150);
          const tex = new THREE.CanvasTexture(off);
          tex.minFilter = THREE.LinearFilter;
          resolve(tex);
        };
        img.src = avatarUrl;
      } catch (e) {
        resolve(null);
      }
    });
  },

  _roundRect(ctx, x, y, w, h, r) {
    const radius = Math.min(r, w / 2, h / 2);
    ctx.beginPath();
    ctx.moveTo(x + radius, y);
    ctx.arcTo(x + w, y, x + w, y + h, radius);
    ctx.arcTo(x + w, y + h, x, y + h, radius);
    ctx.arcTo(x, y + h, x, y, radius);
    ctx.arcTo(x, y, x + w, y, radius);
    ctx.closePath();
  },

  // three 拖动旋转与吸附
  onThreeTouchStart(e) {
    const t = e.touches && e.touches[0];
    if (!t) return;
    this.data._dragState.x0 = t.pageX;
    this.data._dragState.baseAngle = this.data._ringGroup ? this.data._ringGroup.rotation.y : 0;
    this.data._dragState.t0 = Date.now();
    this.data._dragState.moved = false;
  },
  onThreeTouchMove(e) {
    const t = e.touches && e.touches[0];
    if (!t || !this.data._ringGroup) return;
    const dx = t.pageX - this.data._dragState.x0;
    const pxToRad = 0.0045;
    this.data._ringGroup.rotation.y = this.data._dragState.baseAngle - dx * pxToRad;
    if (Math.abs(dx) > 6) this.data._dragState.moved = true;
  },
  onThreeTouchEnd() {
    const group = this.data._ringGroup;
    const list = this.data.recommendationList || [];
    if (!group || !list.length) return;
    const n = list.length;
    const step = (Math.PI * 2) / n;
    const y = group.rotation.y;
    const snapped = Math.round(y / step) * step;
    // 直接设置目标角度：无动量、无缓动
    group.rotation.y = snapped;
  },

  // 根据当前 canvas 尺寸重置渲染器与相机，避免返回后变形
  resizeThreeCanvas() {
    if (!this.data.threeEnabled) return;
    const renderer = this.data._renderer;
    const camera = this.data._camera;
    if (!renderer || !camera) return;

    console.log('[ThreeResize] Triggered resizeThreeCanvas');

    try {
      const applySize = (pass) => {
        const query = wx.createSelectorQuery();
        query.select('#webgl').node().exec(res => {
          console.log(`[ThreeResize Pass ${pass}] Query result:`, res);
          if (!res || !res[0] || !res[0].node) {
            console.warn(`[ThreeResize Pass ${pass}] Could not get canvas node.`);
            return;
          }
          const canvas = res[0].node;
          const sys = wx.getSystemInfoSync();
          const dpr = sys.pixelRatio || 1;
          const logicalW = res[0].width;
          const logicalH = res[0].height;

          console.log(`[ThreeResize Pass ${pass}] System Info: dpr=${dpr}, windowWidth=${sys.windowWidth}`);
          console.log(`[ThreeResize Pass ${pass}] Canvas Node Size: logicalW=${logicalW}, logicalH=${logicalH}`);

          const lw = logicalW < 10 ? Math.max(320, sys.windowWidth - 40) : logicalW;
          const lh = logicalH < 10 ? Math.floor(lw * 0.66) : logicalH;
          
          if (logicalW < 10 || logicalH < 10) {
              console.warn(`[ThreeResize Pass ${pass}] Detected small canvas size, using fallback: lw=${lw}, lh=${lh}`);
          }

          const physicalW = Math.max(1, Math.floor(lw * dpr));
          const physicalH = Math.max(1, Math.floor(lh * dpr));

          console.log(`[ThreeResize Pass ${pass}] Applying sizes: physical=${physicalW}x${physicalH}, logical=${lw}x${lh}`);

          canvas.width = physicalW;
          canvas.height = physicalH;
          renderer.setPixelRatio(dpr);
          renderer.setSize(lw, lh, false);
          camera.aspect = lw / lh;
          camera.updateProjectionMatrix();

          const key = `${lw}x${lh}@${dpr}`;
          if (this._lastCanvasSizeKey !== key) {
            console.log(`[ThreeResize Pass ${pass}] Size key changed from '${this._lastCanvasSizeKey}' to '${key}'. Rebuilding ring.`);
            this._lastCanvasSizeKey = key;
            if (this.data.threeEnabled && this.data._three && this.data._ringGroup && this.data._texLoader) {
              this.buildThreeRing(this.data._three, this.data._ringGroup, this.data._texLoader);
            }
          } else {
            console.log(`[ThreeResize Pass ${pass}] Size key '${key}' is unchanged. No rebuild needed.`);
          }
        });
      };
      setTimeout(() => applySize(1), 40);
      setTimeout(() => applySize(2), 160);
    } catch (e) { 
      console.error('[ThreeResize] Error in resizeThreeCanvas:', e);
    }
  },

  // 3D 环：中心弹跳
  bounceCenterCard(done) {
    const { ringItems } = this.data;
    if (!ringItems || ringItems.length === 0) return typeof done === 'function' && done();
    this.setData({ transitionMs: 160 }, () => {
      const items = ringItems.map((it, idx) => idx === 0 ? { ...it, scale: it.scale * 1.06 } : it);
      this.setData({ ringItems: items });
      setTimeout(() => {
        const back = items.map((it, idx) => idx === 0 ? { ...it, scale: Math.max(it.scale / 1.06, 1.0) } : it);
        this.setData({ ringItems: back, transitionMs: 280 }, () => {
          typeof done === 'function' && done();
        });
      }, 120);
    });
  },

  // 收入范围 多列Picker
  onIncomeMultiPickerChange(e) {
    const [minIdx, maxIdx] = e.detail.value.map(Number);
    const { incomeOptions } = this.data;
    let minI = incomeOptions[minIdx];
    let maxI = incomeOptions[maxIdx];
    if (minI > maxI) [minI, maxI] = [maxI, minI];
    this.setData({
      incomeMinIndex: incomeOptions.indexOf(minI),
      incomeMaxIndex: incomeOptions.indexOf(maxI),
      'filterData.incomeRange.minIncome': minI,
      'filterData.incomeRange.maxIncome': maxI
    });
  },

  // 加载用户列表
  async loadUserList() {
    if (this.data.loading) return;
    
    this.setData({ loading: true });
    
    try {
      const { selectedTab, filterData, pageNum, pageSize } = this.data;
      
      // 构建查询参数
      const params = {
        pageNum,
        pageSize,
        ...this.buildFilterParams(filterData)
      };
      
      // 根据选中的tab调用不同的接口
      let resp;
      if (selectedTab === 'unverified') {
        resp = await api.getUnverifiedUsers(params);
      } else {
        resp = await api.queryUserprofile(params);
      }
      if (!(resp && resp.code === 0 && resp.data && Array.isArray(resp.data.userprofileList))) {
        throw new Error('后端返回格式异常');
      }
      const newUsers = resp.data.userprofileList.map(user => ({
        ...user,
        avatar: util.getDefaultAvatar(user.gender),
        description: `来自${user.hometown}的${user.occupation}，现居${user.currentResidence}`,
        todayFlowerSent: this.data.todayFlowerSent[user.userNum] || false,
        verified: user.verified === 1 // 1:验证过的会员；2:未验证的非会员
      }));

      if (pageNum === 1) {
        this.setData({ userList: newUsers });
      } else {
        this.setData({ 
          userList: [...this.data.userList, ...newUsers] 
        });
      }

      this.setData({
        hasMore: newUsers.length === pageSize,
        pageNum: pageNum + 1
      });

    } catch (error) {
      console.error('加载用户列表失败:', error);
      
      // 提供重试选项
      wx.showModal({
        title: '加载失败',
        content: '网络请求失败，是否重试？',
        confirmText: '重试',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            // 重试
            this.loadUserList();
          }
        }
      });
    } finally {
      this.setData({ loading: false });
      wx.stopPullDownRefresh();
    }
  },


  // 构建筛选参数
  buildFilterParams(filterData) {
    const params = {};

    // 基础项
    if (filterData.gender) params.gender = filterData.gender;
    if (filterData.maritalStatus) params.maritalStatus = filterData.maritalStatus;
    if (filterData.occupation) params.occupation = filterData.occupation;
    if (typeof filterData.parentsHasPension === 'boolean') params.parentsHasPension = filterData.parentsHasPension;

    // 范围项：保持字段名与后端一致（小驼峰）
    const { ageRange, heightRange, weightRange, incomeRange, educationRange } = filterData;

    if ((ageRange.minAge || ageRange.maxAge || ageRange.minBrithday || ageRange.maxBrithday) && ageRange) {
      params.ageRange = { ...ageRange };
    }

    if ((heightRange.minHeight || heightRange.maxHeight) && heightRange) {
      params.heightRange = { ...heightRange };
    }

    if ((weightRange.minWeight || weightRange.maxWeight) && weightRange) {
      params.weightRange = { ...weightRange };
    }

    if ((incomeRange.minIncome || incomeRange.maxIncome) && incomeRange) {
      params.incomeRange = { ...incomeRange };
    }

    if ((educationRange.minEducation || educationRange.maxEducation) && educationRange) {
      params.educationRange = { ...educationRange };
    }

    // 多选项
    if (filterData.hometownPreference && filterData.hometownPreference.length > 0) {
      params.hometownPreference = filterData.hometownPreference;
    }
    if (filterData.currentResidencePreference && filterData.currentResidencePreference.length > 0) {
      params.currentResidencePreference = filterData.currentResidencePreference;
    }

    return params;
  },

  // 刷新数据
  refreshData() {
    this.setData({ 
      pageNum: 1,
      userList: [],
      hasMore: true
    });
    this.loadRecommendations();
    this.loadUserList();
    // 监听窗口尺寸变化，保持 three 画布与相机比例正确
    if (!this._boundOnResize) {
      this._boundOnResize = () => this.resizeThreeCanvas();
      try { wx.onWindowResize && wx.onWindowResize(this._boundOnResize); } catch (e) {}
    }
  },

  // 加载更多数据
  loadMoreData() {
    this.loadUserList();
    // 监听窗口尺寸变化，保持 three 画布与相机比例正确
    if (!this._boundOnResize) {
      this._boundOnResize = () => this.resizeThreeCanvas();
      try { wx.onWindowResize && wx.onWindowResize(this._boundOnResize); } catch (e) {}
    }
  },

  // 推荐卡片点击
  onRecommendationTap(e) {
    const user = e.currentTarget.dataset.user;
    wx.navigateTo({
      url: `/pages/profile/profile?userNum=${user.userNum}`
    });
  },

  // 用户卡片点击
  onUserCardTap(e) {
    const user = e.currentTarget.dataset.user;
    // 防止事件冒泡到送花按钮
    if (e.target.dataset.userNum) return;
    
    wx.navigateTo({
      url: `/pages/profile/profile?userNum=${user.userNum}`
    });
  },

  // 送花按钮点击
  async onSendFlower(e) {
    e.stopPropagation();
    
    const userNum = e.currentTarget.dataset.userNum;
    const currentUser = app.globalData.currentUser;
    
    // 检查登录状态
    if (!currentUser.isLogin) {
      await this.handleLogin();
    }
    
    try {
      wx.showLoading({ title: '送花中...' });
      
      // 调用送花API
      await api.sendFlower(currentUser.userNum, userNum);
      
      // 更新本地送花状态
      const todayFlowerKey = `todayFlower_${util.formatDate(new Date())}`;
      const todayFlowerSent = wx.getStorageSync(todayFlowerKey) || {};
      todayFlowerSent[userNum] = true;
      wx.setStorageSync(todayFlowerKey, todayFlowerSent);
      
      this.setData({ todayFlowerSent });
      this.updateFlowerStatus();
      
      wx.showToast({
        title: '送花成功！',
        icon: 'success'
      });
      
    } catch (error) {
      console.error('送花失败:', error);
      wx.showToast({
        title: '送花失败',
        icon: 'error'
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 处理登录
  async handleLogin() {
    try {
      // 先调用微信登录
      const code = await app.login();
      
      // 获取用户手机号授权
      await new Promise((resolve, reject) => {
        wx.showModal({
          title: '登录提示',
          content: '需要获取您的手机号来完成登录',
          confirmText: '立即登录',
          cancelText: '暂不登录',
          success: (res) => {
            if (res.confirm) {
              resolve();
            } else {
              reject(new Error('用户取消登录'));
            }
          }
        });
      });
      
      console.log('登录成功');
      
    } catch (error) {
      console.error('登录失败:', error);
      throw error;
    }
  },

  // 筛选按钮点击
  onFilterTap() {
    this.setData({ showFilterModal: true });
  },

  // 关闭筛选面板
  onFilterModalClose() {
    this.setData({ showFilterModal: false });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 空函数，用于阻止事件冒泡
  },

  // 拖拽过程更新坐标（movable-view change）
  onSearchMove(e) {
    const { x, y } = e.detail || {};
    if (typeof x === 'number' && typeof y === 'number') {
      this.setData({ searchIconX: x, searchIconY: y });
    }
  },

  // 拖拽结束，持久化搜索图标位置
  onSearchDragEnd() {
    const { searchIconX: x, searchIconY: y } = this.data;
    wx.setStorageSync('searchIconPos', { x, y });
  },

  // 性别选择
  onGenderChange(e) {
    const gender = e.currentTarget.dataset.value;
    this.setData({
      'filterData.gender': this.data.filterData.gender === gender ? '' : gender
    });
  },

  // 性别 Picker 选择
  onGenderPickerChange(e) {
    const idx = Number(e.detail.value);
    const gender = this.data.genderOptions[idx];
    this.setData({ genderIndex: idx, 'filterData.gender': gender });
  },

  // 年龄范围改变
  onAgeRangeChange(e) {
    const type = e.currentTarget.dataset.type;
    const value = e.detail.value;
    this.setData({
      [`filterData.ageRange.${type}`]: value
    });
  },

  // 年龄范围 多列Picker
  onAgeMultiPickerChange(e) {
    const [minIdx, maxIdx] = e.detail.value.map(Number);
    const { ageOptions } = this.data;
    let minAge = ageOptions[minIdx];
    let maxAge = ageOptions[maxIdx];
    if (minAge > maxAge) {
      // 确保最小不大于最大
      [minAge, maxAge] = [maxAge, minAge];
    }
    this.setData({
      ageMinIndex: ageOptions.indexOf(minAge),
      ageMaxIndex: ageOptions.indexOf(maxAge),
      'filterData.ageRange.minAge': minAge,
      'filterData.ageRange.maxAge': maxAge
    });
  },

  // 身高范围改变
  onHeightRangeChange(e) {
    const type = e.currentTarget.dataset.type;
    const value = e.detail.value;
    this.setData({
      [`filterData.heightRange.${type}`]: value
    });
  },

  // 收入范围改变
  onIncomeRangeChange(e) {
    const type = e.currentTarget.dataset.type;
    const value = e.detail.value;
    this.setData({
      [`filterData.incomeRange.${type}`]: value
    });
  },

  // 学历选择
  onEducationChange(e) {
    const index = e.detail.value;
    const education = this.data.educationOptions[index];
    this.setData({
      educationIndex: index,
      'filterData.educationRange.minEducation': education
    });
  },

  // 学历 最低 Picker
  onEduMinPickerChange(e) {
    const idx = Number(e.detail.value);
    const edu = this.data.educationOptions[idx];
    this.setData({ eduMinIndex: idx, 'filterData.educationRange.minEducation': edu });
  },

  // 学历 最高 Picker
  onEduMaxPickerChange(e) {
    const idx = Number(e.detail.value);
    const edu = this.data.educationOptions[idx];
    this.setData({ eduMaxIndex: idx, 'filterData.educationRange.maxEducation': edu });
  },

  // 籍贯列变化事件处理（实现联动）
  onHometownColumnChange(e) {
    const { column, value } = e.detail;
    const { provinceOptions, hometownProvinceIndex, hometownCityIndex } = this.data;
    
    if (column === 0) {
      // 省份改变，更新城市和区县选项
      const province = provinceOptions[value];
      const newCityOptions = regionSelector.getCitiesByProvince(province);
      const newDistrictOptions = newCityOptions.length > 0 ? 
        regionSelector.getDistrictsByCity(province, newCityOptions[0]) : [];
      
      this.setData({
        hometownProvinceIndex: value,
        hometownCityIndex: 0,
        hometownDistrictIndex: 0,
        hometownCityOptions: newCityOptions,
        hometownDistrictOptions: newDistrictOptions,
        hometownSelectedText: regionSelector.buildFullAddress(province, newCityOptions[0] || '', newDistrictOptions[0] || '')
      });
    } else if (column === 1) {
      // 城市改变，更新区县选项
      const province = provinceOptions[hometownProvinceIndex];
      const city = this.data.hometownCityOptions[value];
      const newDistrictOptions = regionSelector.getDistrictsByCity(province, city);
      
      this.setData({
        hometownCityIndex: value,
        hometownDistrictIndex: 0,
        hometownDistrictOptions: newDistrictOptions,
        hometownSelectedText: regionSelector.buildFullAddress(province, city, newDistrictOptions[0] || '')
      });
    } else if (column === 2) {
      // 区县改变，更新显示文本
      const province = provinceOptions[hometownProvinceIndex];
      const city = this.data.hometownCityOptions[hometownCityIndex];
      const district = this.data.hometownDistrictOptions[value];
      
      this.setData({
        hometownDistrictIndex: value,
        hometownSelectedText: regionSelector.buildFullAddress(province, city, district)
      });
    }
  },

  // 省市区三级联动 - 籍贯（确认选择）
  onHometownRegionChange(e) {
    const [provinceIndex, cityIndex, districtIndex] = e.detail.value;
    const { provinceOptions, hometownCityOptions, hometownDistrictOptions } = this.data;
    
    const province = provinceOptions[provinceIndex];
    const city = hometownCityOptions[cityIndex];
    const district = hometownDistrictOptions[districtIndex];
    
    // 添加到籍贯偏好
    const address = {
      province: province,
      city: city,
      district: district,
      fullName: regionSelector.buildFullAddress(province, city, district)
    };
    
    let { hometownPreference } = this.data.filterData;
    const existingIndex = hometownPreference.findIndex(item => 
      (typeof item === 'object' ? item.fullName : item) === address.fullName
    );
    
    if (existingIndex === -1) {
      hometownPreference = [...hometownPreference, address];
      this.setData({
        'filterData.hometownPreference': hometownPreference
      });
    }
  },

  // 常见地址快速选择 - 籍贯
  onSelectCommonHometown(e) {
    const address = e.currentTarget.dataset.address;
    
    // 更新省市区索引
    const provinceIndex = this.data.provinceOptions.indexOf(address.province);
    const cityOptions = regionSelector.getCitiesByProvince(address.province);
    const cityIndex = cityOptions.indexOf(address.city);
    const districtOptions = regionSelector.getDistrictsByCity(address.province, address.city);
    const districtIndex = districtOptions.indexOf(address.district);
    
    this.setData({
      hometownProvinceIndex: provinceIndex,
      hometownCityIndex: cityIndex,
      hometownDistrictIndex: districtIndex,
      hometownCityOptions: cityOptions,
      hometownDistrictOptions: districtOptions,
      hometownSelectedText: address.fullName
    });
    
    // 添加到籍贯偏好
    let { hometownPreference } = this.data.filterData;
    const existingIndex = hometownPreference.findIndex(item => 
      (typeof item === 'object' ? item.fullName : item) === address.fullName
    );
    
    if (existingIndex === -1) {
      hometownPreference = [...hometownPreference, address];
      this.setData({
        'filterData.hometownPreference': hometownPreference
      });
    }
  },

  // 现居地列变化事件处理（实现联动）
  onResidenceColumnChange(e) {
    const { column, value } = e.detail;
    const { provinceOptions, residenceProvinceIndex, residenceCityIndex } = this.data;
    
    if (column === 0) {
      // 省份改变，更新城市和区县选项
      const province = provinceOptions[value];
      const newCityOptions = regionSelector.getCitiesByProvince(province);
      const newDistrictOptions = newCityOptions.length > 0 ? 
        regionSelector.getDistrictsByCity(province, newCityOptions[0]) : [];
      
      this.setData({
        residenceProvinceIndex: value,
        residenceCityIndex: 0,
        residenceDistrictIndex: 0,
        residenceCityOptions: newCityOptions,
        residenceDistrictOptions: newDistrictOptions,
        residenceSelectedText: regionSelector.buildFullAddress(province, newCityOptions[0] || '', newDistrictOptions[0] || '')
      });
    } else if (column === 1) {
      // 城市改变，更新区县选项
      const province = provinceOptions[residenceProvinceIndex];
      const city = this.data.residenceCityOptions[value];
      const newDistrictOptions = regionSelector.getDistrictsByCity(province, city);
      
      this.setData({
        residenceCityIndex: value,
        residenceDistrictIndex: 0,
        residenceDistrictOptions: newDistrictOptions,
        residenceSelectedText: regionSelector.buildFullAddress(province, city, newDistrictOptions[0] || '')
      });
    } else if (column === 2) {
      // 区县改变，更新显示文本
      const province = provinceOptions[residenceProvinceIndex];
      const city = this.data.residenceCityOptions[residenceCityIndex];
      const district = this.data.residenceDistrictOptions[value];
      
      this.setData({
        residenceDistrictIndex: value,
        residenceSelectedText: regionSelector.buildFullAddress(province, city, district)
      });
    }
  },

  // 省市区三级联动 - 现居地（确认选择）
  onResidenceRegionChange(e) {
    const [provinceIndex, cityIndex, districtIndex] = e.detail.value;
    const { provinceOptions, residenceCityOptions, residenceDistrictOptions } = this.data;
    
    const province = provinceOptions[provinceIndex];
    const city = residenceCityOptions[cityIndex];
    const district = residenceDistrictOptions[districtIndex];
    
    // 添加到现居地偏好
    const address = {
      province: province,
      city: city,
      district: district,
      fullName: regionSelector.buildFullAddress(province, city, district)
    };
    
    let { currentResidencePreference } = this.data.filterData;
    const existingIndex = currentResidencePreference.findIndex(item => 
      (typeof item === 'object' ? item.fullName : item) === address.fullName
    );
    
    if (existingIndex === -1) {
      currentResidencePreference = [...currentResidencePreference, address];
      this.setData({
        'filterData.currentResidencePreference': currentResidencePreference
      });
    }
  },

  // 常见地址快速选择 - 现居地
  onSelectCommonResidence(e) {
    const address = e.currentTarget.dataset.address;
    
    // 更新省市区索引
    const provinceIndex = this.data.provinceOptions.indexOf(address.province);
    const cityOptions = regionSelector.getCitiesByProvince(address.province);
    const cityIndex = cityOptions.indexOf(address.city);
    const districtOptions = regionSelector.getDistrictsByCity(address.province, address.city);
    const districtIndex = districtOptions.indexOf(address.district);
    
    this.setData({
      residenceProvinceIndex: provinceIndex,
      residenceCityIndex: cityIndex,
      residenceDistrictIndex: districtIndex,
      residenceCityOptions: cityOptions,
      residenceDistrictOptions: districtOptions,
      residenceSelectedText: address.fullName
    });
    
    // 添加到现居地偏好
    let { currentResidencePreference } = this.data.filterData;
    const existingIndex = currentResidencePreference.findIndex(item => 
      (typeof item === 'object' ? item.fullName : item) === address.fullName
    );
    
    if (existingIndex === -1) {
      currentResidencePreference = [...currentResidencePreference, address];
      this.setData({
        'filterData.currentResidencePreference': currentResidencePreference
      });
    }
  },

  // 籍贯选择（保留原有功能兼容性）
  onHometownChange(e) {
    const value = e.currentTarget.dataset.value;
    let { hometownPreference } = this.data.filterData;
    
    if (hometownPreference.includes(value)) {
      hometownPreference = hometownPreference.filter(item => item !== value);
    } else {
      hometownPreference = [...hometownPreference, value];
    }
    
    this.setData({
      'filterData.hometownPreference': hometownPreference
    });
  },

  // 现居地选择
  onResidenceChange(e) {
    const value = e.currentTarget.dataset.value;
    let { currentResidencePreference } = this.data.filterData;
    
    if (currentResidencePreference.includes(value)) {
      currentResidencePreference = currentResidencePreference.filter(item => item !== value);
    } else {
      currentResidencePreference = [...currentResidencePreference, value];
    }
    
    this.setData({
      'filterData.currentResidencePreference': currentResidencePreference
    });
  },

  // 移除已选籍贯
  onRemoveHometownTag(e) {
    const value = e.currentTarget.dataset.value;
    const currentList = this.data.filterData.hometownPreference || [];
    
    // 支持删除对象类型和字符串类型的地址
    const next = currentList.filter(item => {
      if (typeof item === 'object' && typeof value === 'object') {
        return item.fullName !== value.fullName;
      } else if (typeof item === 'object') {
        return item.fullName !== value;
      } else if (typeof value === 'object') {
        return item !== value.fullName;
      } else {
        return item !== value;
      }
    });
    
    this.setData({ 'filterData.hometownPreference': next });
  },

  // 移除已选现居地
  onRemoveResidenceTag(e) {
    const value = e.currentTarget.dataset.value;
    const currentList = this.data.filterData.currentResidencePreference || [];
    
    // 支持删除对象类型和字符串类型的地址
    const next = currentList.filter(item => {
      if (typeof item === 'object' && typeof value === 'object') {
        return item.fullName !== value.fullName;
      } else if (typeof item === 'object') {
        return item.fullName !== value;
      } else if (typeof value === 'object') {
        return item !== value.fullName;
      } else {
        return item !== value;
      }
    });
    
    this.setData({ 'filterData.currentResidencePreference': next });
  },

  // 重置筛选
  onFilterReset() {
    this.setData({
      filterData: {
        gender: '',
        ageRange: { minAge: 18, maxAge: 60 },
        heightRange: { minHeight: 150, maxHeight: 200 },
        weightRange: { minWeight: 80, maxWeight: 200 },
        maritalStatus: '',
        educationRange: { minEducation: '', maxEducation: '' },
        incomeRange: { minIncome: 0, maxIncome: 100 },
        occupation: '',
        hometownPreference: [],
        currentResidencePreference: [],
        parentsHasPension: false
      },
      educationIndex: 0,
      genderIndex: 0,
      maritalStatusIndex: 0,
      occupationIndex: 0,
      eduMinIndex: 0,
      eduMaxIndex: 0,
      ageMinIndex: 0,
      ageMaxIndex: this.data.ageOptions.length - 1
    });
  },

  // 清空筛选（等效重置，但不关闭面板）
  onFilterClearAll() {
    this.onFilterReset();
  },

  // 婚姻状态 Picker
  onMaritalStatusPickerChange(e) {
    const idx = Number(e.detail.value);
    const val = this.data.maritalStatusOptions[idx];
    this.setData({ maritalStatusIndex: idx, 'filterData.maritalStatus': val });
  },

  // 职业 Picker（可用于选择“体制内”等，后端支持模糊）
  onOccupationPickerChange(e) {
    const idx = Number(e.detail.value);
    const val = this.data.occupationOptions[idx];
    this.setData({ occupationIndex: idx, 'filterData.occupation': val });
  },

  // 打开职业搜索弹层
  onOpenOccupationSearch() {
    const list = this.data.occupationOptions || [];
    this.setData({
      showOccupationModal: true,
      occupationSearchQuery: '',
      filteredOccupationOptions: list
    });
  },

  // 输入职业关键词过滤
  onOccupationSearchInput(e) {
    const q = (e.detail.value || '').trim();
    const base = this.data.occupationOptions || [];
    const filtered = q ? base.filter(it => it.indexOf(q) !== -1) : base;
    this.setData({ occupationSearchQuery: q, filteredOccupationOptions: filtered });
  },

  // 选择职业
  onSelectOccupation(e) {
    const val = e.currentTarget.dataset.value;
    const idx = (this.data.occupationOptions || []).indexOf(val);
    this.setData({
      'filterData.occupation': val,
      occupationIndex: idx >= 0 ? idx : 0,
      showOccupationModal: false
    });
  },

  // 关闭职业搜索弹层
  onCloseOccupationSearch() {
    this.setData({ showOccupationModal: false });
  },

  // 确认筛选
  onFilterConfirm() {
    this.setData({ 
      showFilterModal: false,
      pageNum: 1,
      userList: [],
      hasMore: true
    });
    this.loadUserList();
  },

  // 重试加载
  onRetryLoad() {
    this.setData({ 
      networkError: false,
      showNetworkStatus: false,
      pageNum: 1,
      userList: [],
      hasMore: true
    });
    this.checkNetworkAndLoadData();
  },

  // 重试网络连接
  onRetryNetwork() {
    this.setData({ showNetworkStatus: false });
    this.checkNetworkAndLoadData();
  },

  // ==================== 3D环形Swiper交互 ====================
  
  // Swiper切换事件
  onSwiperChange(e) {
    const current = e.detail.current;
    this.setData({ swiperCurrent: current });
    console.log('Swiper切换到:', current);
  },

  // Swiper触摸开始
  onSwiperTouchStart(e) {
    console.log('Swiper触摸开始');
  },

  // Swiper触摸移动
  onSwiperTouchMove(e) {
    console.log('Swiper触摸移动');
  },

  // Swiper触摸结束
  onSwiperTouchEnd(e) {
    console.log('Swiper触摸结束');
  },

  // 环形卡片点击
  onRingCardTap(e) {
    const index = e.currentTarget.dataset.index;
    const user = this.data.recommendationList[index];
    if (user) {
      console.log('点击环形卡片:', user);
      wx.navigateTo({
        url: `/pages/profile/profile?userNum=${user.userNum}`
      });
    }
  },

  // 指示器点击
  onIndicatorTap(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({ swiperCurrent: index });
    console.log('点击指示器切换到:', index);
  }
});